<template>
  <el-config-provider :locale="zhCn">
  <div class="page">
    <div class="toolbar">
      <el-form :inline="true" :model="filters" class="filters">
        <el-form-item label="活动名称">
          <el-input v-model="filters.name" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="活动类型">
          <el-select v-model="filters.activity_type_id" placeholder="请选择" clearable style="min-width:200px">
            <el-option v-for="t in activityTypes" :key="t.code" :label="t.name" :value="t.code" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="reload">查询</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-area">
      <div class="table-container">
        <el-table :data="items" style="width:100%" max-height="100%">
          <el-table-column prop="name" label="名称" min-width="160" />
          <el-table-column label="类型" min-width="160">
            <template #default="{ row }">{{ idToName[row.activity_type_id] || row.activity_type_id }}</template>
          </el-table-column>
          <el-table-column label="关联指标" min-width="180">
            <template #default="{ row }">{{ versionName[row.indicator_version_id || ''] || '-' }}</template>
          </el-table-column>
          <el-table-column label="评分" min-width="120">
            <template #default="{ row }">{{ latestVeto[row.id] ? '否决' : (latestScores[row.id] ?? '-') }}</template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="300">
            <template #default="{ row }">
              <el-button @click="linkIndicator(row)">关联指标</el-button>
              <el-button type="primary" @click="onScore(row)">打分</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-config-provider :locale="zhCn">
          <el-pagination
            background
            layout="prev, pager, next, sizes, jumper, total"
            :total="total"
            :page-size="pageSize"
            :current-page="page"
            :page-sizes="[10,20,50,100]"
            @size-change="onSizeChange"
            @current-change="onPageChange"
          />
        </el-config-provider>
      </div>
    </div>

    <el-dialog v-model="showLinkDialog" title="关联指标体系" width="520px" destroy-on-close>
      <el-form :model="linkForm" label-width="110px">
        <el-form-item label="活动名称"><span>{{ linkActivity?.name || '-' }}</span></el-form-item>
        <el-form-item label="活动类型"><span>{{ idToName[linkActivity?.activity_type_id || ''] || '-' }}</span></el-form-item>
        <el-form-item label="指标版本">
          <el-select v-model="linkForm.indicator_version_id" placeholder="请选择" style="min-width:100%">
            <el-option v-for="v in eligibleVersions" :key="v.id" :label="v.name + ' (' + v.version_code + ')'" :value="v.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showLinkDialog=false">取消</el-button>
        <el-button type="primary" :loading="linking" @click="confirmLink">确定</el-button>
      </template>
    </el-dialog>
  </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { api } from '../../api/client'

type Activity = {
  id: string
  name: string
  activity_type_id: string
  indicator_version_id?: string | null
}

type DictItem = { id: string; code: string; name: string }
type IndicatorVersion = { id: string; version_code: string; name: string; activity_types?: { id: string; code: string; name: string }[] }

const items = ref<Activity[]>([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

const activityTypes = ref<DictItem[]>([])
const codeToId = ref<Record<string, string>>({})
const idToName = ref<Record<string, string>>({})

const versions = ref<IndicatorVersion[]>([])
const versionName = ref<Record<string, string>>({})
const latestScores = ref<Record<string, number>>({})
const latestVeto = ref<Record<string, boolean>>({})

const filters = reactive({
  name: '',
  activity_type_id: ''
})

function resetFilters() {
  filters.name = ''
  filters.activity_type_id = ''
}

async function load() {
  const params: any = { page: page.value, page_size: pageSize.value }
  if (filters.name) params.name = filters.name
  if (filters.activity_type_id) params.activity_type_id = codeToId.value[filters.activity_type_id] || filters.activity_type_id
  const res = await api.get('/activities', { params })
  const data = res.data
  items.value = Array.isArray(data.items) ? data.items : Array.isArray(data) ? data : []
  total.value = typeof data.total === 'number' ? data.total : typeof data.total_count === 'number' ? data.total_count : Number(res.headers['x-total-count'] ?? items.value.length)
  await loadLatestScores()
}

async function loadActivityTypes() {
  const { data } = await api.get('/dictionaries/items', { params: { type_code: 'activity_type', page_size: 200 } })
  activityTypes.value = data
  const c2i: Record<string, string> = {}
  const i2n: Record<string, string> = {}
  data.forEach((d: DictItem) => { c2i[d.code] = d.id; i2n[d.id] = d.name })
  codeToId.value = c2i
  idToName.value = i2n
}

async function loadVersions() {
  const { data } = await api.get('/indicators/versions')
  versions.value = data
  const vn: Record<string, string> = {}
  data.forEach((v: IndicatorVersion) => { vn[v.id] = v.name + ' (' + v.version_code + ')' })
  versionName.value = vn
}

async function loadLatestScores() {
  const map: Record<string, number> = {}
  const vmap: Record<string, boolean> = {}
  await Promise.all(items.value.map(async (row) => {
    try {
      const { data } = await api.get('/evaluations/latest', { params: { activity_id: row.id } })
      map[row.id] = data.score_total
      vmap[row.id] = Boolean(data?.verdict)
    } catch {}
  }))
  latestScores.value = map
  latestVeto.value = vmap
}

function reload() {
  page.value = 1
  load()
}

function onPageChange(p: number) {
  page.value = p
  load()
}

function onSizeChange(s: number) {
  pageSize.value = s
  page.value = 1
  load()
}

const showLinkDialog = ref(false)
const linking = ref(false)
const linkForm = reactive<{ activity_id: string; indicator_version_id: string | '' }>({ activity_id: '', indicator_version_id: '' })
const linkActivity = ref<Activity | null>(null)
const eligibleVersions = ref<IndicatorVersion[]>([])

function onScore(row: Activity) {
  window.location.href = `/admin/activity-scoring/${row.id}`
}

function linkIndicator(row: Activity) {
  linkActivity.value = row
  linkForm.activity_id = row.id
  linkForm.indicator_version_id = ''
  eligibleVersions.value = versions.value.filter(v => (v.activity_types || []).some(t => t.id === row.activity_type_id))
  showLinkDialog.value = true
}

async function confirmLink() {
  if (!linkForm.activity_id || !linkForm.indicator_version_id) return
  linking.value = true
  try {
    await api.patch(`/activities/${linkForm.activity_id}/indicator-version`, { indicator_version_id: linkForm.indicator_version_id })
    showLinkDialog.value = false
    await load()
  } finally { linking.value = false }
}

onMounted(async () => {
  await Promise.all([loadActivityTypes(), loadVersions()])
  await load()
})
</script>

<style scoped>
.page { height: 100%; display: flex; flex-direction: column; box-sizing: border-box; overflow: hidden; }
.toolbar { flex-shrink: 0; padding: 12px 16px; background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light) }
.filters { display: flex; flex-wrap: wrap; gap: 12px; }
.table-area { flex: 1; min-height: 0; display: flex; flex-direction: column; }
.table-container { flex: 1; min-height: 0; padding: 10px 16px; }
.pagination { flex-shrink: 0; padding: 6px 16px; border-top: 1px solid var(--el-border-color-light); }
:deep(.pagination) { display: flex; justify-content: flex-end; }
:deep(.el-table__inner-wrapper) { height: 100%; display: flex; flex-direction: column; }
:deep(.el-table__body-wrapper) { flex: 1; }
</style>